/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Business.RecordDBUtil;

import Business.Record.Record;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.ta.TransparentPersistenceSupport;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author raunak
 */
public class RecordDBUtil {

    //Change the FILENAME to the path where you have saved your DB4O serialization file
    private static final String FILENAME = "db/DataRecord.db";
    

    /*
    * Reads the Db4O file and creates and returns an ObjectContainer object
    * @return ObjectContainer
    */
    private ObjectContainer createConnection() {
       try {
           EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
           config.common().add(new TransparentPersistenceSupport());
           //Controls the number of objects in memory
           config.common().activationDepth(Integer.MAX_VALUE);
           //Controls the depth/level of updation of Object
           config.common().updateDepth(Integer.MAX_VALUE);

           //Register your top most Class here
           config.common().objectClass(Record.class).cascadeOnUpdate(true);

           ObjectContainer db = Db4oEmbedded.openFile(config, FILENAME);
           return db;
       } catch (Exception ex) {
           System.out.println(ex.getMessage());
	       ex.printStackTrace();
       }
       return null;
    }

    /*
     * Serializes and stores the {@code EcoSystem} object inside the DB4O database file
     */
    public synchronized void insertRecord(Record r){
        ObjectContainer conn = createConnection();
		if(conn == null){
			System.out.println("null in insertRecord");
		}
		conn.store(r);
        conn.commit();
        conn.close();
    }
    
    /*
     * Reads and deserializes the {@code EcoSystem} object from DB4O database file and returns
     * the object
     * @return EcoSystem
     */
    public List<Record> retrieveAllRecords(){
        ObjectContainer conn = createConnection();
		if(conn == null){
			System.out.println("null in retrieveRecords");
		}
        ObjectSet<Record> systems = conn.query(Record.class);
        List<Record> l = new ArrayList<Record>();
		for(int i = 0; i < systems.size(); i++){
			l.add(systems.get(i));
		}
        conn.close();
        return l;
    }

	public void deleteRecord(Record r){
		ObjectContainer conn = createConnection();
		ObjectSet result = conn.queryByExample(r);
		Record found = (Record)result.next();
		conn.delete(found);
		conn.commit();
		conn.close();
	}
}

